package com.mingte.manghe.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.concurrent.*;

/**
 * @author ：luxinsheng
 * @Email ：282860642@qq.com
 * @date ：Created in 2021/11/25 10:32
 * @description：线程池配置
 * @modified By：
 * @version: $
 */

@Component
public class ThreadPoolConfig {

    private final Logger logger = LoggerFactory.getLogger(ThreadPoolConfig.class);

    private ExecutorService pool;

    @PostConstruct
    private void initThreadPool(){
        pool = new ThreadPoolExecutor(20,100, 6000L,TimeUnit.MICROSECONDS,
                new LinkedBlockingDeque<>(), new ThreadPoolExecutor.DiscardOldestPolicy());

        if(pool != null){
            logger.info("线程池初始化完成");
        }else{
            logger.info("线程池初始化失败");
        }
    }

    public ExecutorService getPool() {
        return pool;
    }

    /**
     * 提交任务
     * @param runnable
     * @return
     */
    public Future<?> submit(Runnable runnable){
        Future<?> submitResult = null;
        if(null != runnable){
            submitResult = pool.submit(runnable);
        }
        return submitResult;
    }


    /**
     * 提交任务
     * @param runnable
     * @return
     */
    public void execute(Runnable runnable){
        if(null != runnable){
            pool.execute(runnable);
        }
    }

    /**
     * 关闭
     * @return
     */
    public List<Runnable> shutdown(){
        logger.info("Thread-pool is closing...");
        return pool.shutdownNow();
    }
}
